<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/10/23
 * Time: 11:30 PM
 */
namespace app\api\controller\v1;
use app\api\model\Address as AddressModel;
use app\api\model\User as UserModel;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessException;
use app\lib\exception\UserException;

class Address extends Base {

   public function createOrUpdateAddress(){
       $validate = new AddressNew();
       $validate->goCheck();
       $uid = \app\lib\Token::getDataForToken('id');
       $user = UserModel::get($uid);
       if(!$user){
           throw new UserException();
       }
       $userAddress = AddressModel::where("user_id",$uid)->find();
       $dataArr = $validate->getDataByRule(input('post.'));
       $dataArr['user_id'] = $user['id'];
       if(!$userAddress){
           $userAddress = new AddressModel();
           $userAddress->create($dataArr);
       }else{
           $userAddress->save($dataArr);
       }
       return new SuccessException();
   }


    /**
     * 获取用户地址信息
     * @return UserAddress
     * @throws UserException
     */
    public function getUserAddress(){
        $uid = \app\lib\Token::getDataForToken('id');
        $userAddress = AddressModel::where('user_id', $uid)
            ->find();
        if(!$userAddress){
            throw new UserException([
                'msg' => '用户地址不存在',
                'errorCode' => 60001
            ]);
        }
        return $userAddress;
    }



}